<?php
// functions for front-end uses

add_filter('the_content', 'run_spinner');

function spinParse($pos, &$data) {

    global $leftchar, $rightchar, $escape_char;
    $startPos = $pos;
    $left = strlen($leftchar);
    $right = strlen($rightchar);
    $esc = strlen($escape_char);
    //print "Start Position: $startPos | Length: ".strlen($data)."<br>";

    while ($pos++ < strlen($data)) {
        //print "Current Position: $pos | Character: ".substr($data, $pos, 1)."<br>";

        //Escape left/right char
        if (substr($data, $pos, $esc) == $escape_char && (substr($data, $pos + $esc, $left) == $leftchar || substr($data, $pos + $esc, $right) == $rightchar)) {
            $pos += $esc;
            continue;
        }

        if (substr($data, $pos, $left) == $leftchar) {
            $data = spinParse($pos, $data);
        } elseif (substr($data, $pos, $right) == $rightchar) {
            $entirespinner = substr($data, $startPos + $left, ($pos - $startPos) - $right);
            $processed = spinProcess($entirespinner);
            $data = substr_replace($data, $processed, $startPos, strlen($entirespinner) + $left + $right);
            break;
        }

        //echo ($data."<br>");
    }
    return $data;
}


function spinProcess($input) {
    global $splitchar, $escape_char, $wv;

    //Escape split char
    $temp = '@#!_' . time();    //Unique delimiter
    $input = str_replace($escape_char . $splitchar, $temp, $input);
    $txt = split($splitchar, $input);

    $selection = $txt[mt_rand(0, count($txt) - 1)];

	$wv->possible_texts = $wv->possible_texts * count($txt);
    $selection = str_replace($temp, $splitchar, $selection);
    //echo (" | Result: '$selection'<br>");
    return $selection;
}


function run_spinner($text) {
    global $leftchar, $rightchar, $splitchar, $escape_char;

    $leftchar = get_option('wspin_leftchar');
    $rightchar = get_option('wspin_rightchar');
    $splitchar = get_option('wspin_splitchar');
    $escape_char = '\\';

    //echo ("<br><br>Exec time: ".(time()-$startTime)." seconds.");
    $text = spinParse(-1, $text);
    $text = str_replace($escape_char . $leftchar, $leftchar, $text);
    $text = str_replace($escape_char . $rightchar, $rightchar, $text);

    return $text;
}

function wv_trim_excerpt($text, $length = 30, $excerpt = '...') {
    $words = explode(' ', $text, $length + 1);
    if (count($words) > $length) {
        array_pop($words);
        array_push($words, $excerpt);
        $text = implode(' ', $words);
    }
    return $text;
}

?>
